package ngamejava2;

import java.awt.Graphics2D;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

public class GamePlane extends GameObjectContainer<PlaneManager, GameObject>
{
	private ArrayList<GameObject> objectsToRemove;

	public GamePlane()
	{
		super();
		setCollidable(false);
		objectsToRemove = new ArrayList<GameObject>();
	}

	@Override
	public void load()
	{
		resetIterator();
		while (iteratorHasNext())
		{
			getCurrentObject().load();
		}
	}

        	@Override
	public void unload()
	{
		resetIterator();
		while (iteratorHasNext())
		{
			getCurrentObject().unload();
		}
	}

	@Override
	public void update(long currentTick)
	{

		objectsToRemove.clear();
		resetIterator();
		while (iteratorHasNext())
		{
			getCurrentObject().update(currentTick);
			if (getCurrentObject().isDiscarted())
			{
				objectsToRemove.add(getCurrentObject());
			}
		}
		removeAll(objectsToRemove);
	}

	@Override
	public void render(Graphics2D g, long currentFrame)
	{
		resetIterator();
		while (iteratorHasNext())
		{
			if (!getCurrentObject().isDiscarted() && getBounds().intersects(getCurrentObject().getBounds()))
			{
				getCurrentObject().render(g, currentFrame);
			}
		}
	}

	public GameObject getFirstInsersecting(GameObject aGameObject)
	{
		return getFirstInsersecting(aGameObject, null);
	}

	public GameObject getFirstInsersecting(GameObject aGameObject, Rectangle2D.Float intersectionRect)
	{
		resetIterator();
		while (iteratorHasNext())
		{
			if (getCurrentObject().isCollidable() && !getCurrentObject().isDiscarted() && getCurrentObject() != aGameObject)
			{
				Rectangle2D.Float r = (Rectangle2D.Float) getCurrentObject().getBounds().createIntersection(aGameObject.getBounds());
				if (r.width > 0 && r.height > 0)
				{
					if (intersectionRect != null)
					{
						intersectionRect.setRect(r);
					}
					if (getCurrentObject() instanceof PlatformObject)
					{
						Area tmp = new Area(((PlatformObject)getCurrentObject()).getArea());
						if (tmp.intersects(aGameObject.getBounds()))
						{
							tmp.intersect(new Area(aGameObject.getBounds()));
							if (intersectionRect != null)
							{
								intersectionRect.setRect(tmp.getBounds2D());
							}
							return getCurrentObject();
						}
					}
					else
					{
						return getCurrentObject();
					}
				}
			}
		}
		return null;
	}
}